<template>
  <div class="my-posts">
    <div class="page-header">
      <h2>我的文章</h2>
      <el-button type="primary" @click="handleCreate">写文章</el-button>
    </div>

    <el-table v-loading="loading" :data="posts" style="width: 100%">
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="city" label="城市" width="120" />
      <el-table-column prop="viewCount" label="阅读量" width="100" align="center" />
      <el-table-column prop="createdTime" label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建/编辑文章对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingPost ? '编辑文章' : '创建文章'"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="postForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="postForm.title" />
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-input v-model="postForm.coverImage" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="postForm.city" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="postForm.category" placeholder="请选择分类">
            <el-option label="旅游攻略" value="旅游攻略" />
            <el-option label="游记" value="游记" />
            <el-option label="美食推荐" value="美食推荐" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="10"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { userPostApi } from '@/api/user/post'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import type { Post } from '@/types/post'
import dayjs from 'dayjs'

const loading = ref(false)
const submitting = ref(false)
const posts = ref<Post[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const editingPost = ref<Post | null>(null)
const formRef = ref<FormInstance>()

const postForm = ref({
  title: '',
  coverImage: '',
  content: '',
  city: '',
  category: ''
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  coverImage: [{ required: true, message: '请输入封面图URL', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

const fetchPosts = async () => {
  loading.value = true
  try {
    const response = await userPostApi.getMyPosts({
      page: currentPage.value - 1,
      size: pageSize.value
    })
    if (response.data.code === 200) {
      posts.value = response.data.data.content
      total.value = response.data.data.totalElements
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  editingPost.value = null
  postForm.value = {
    title: '',
    coverImage: '',
    content: '',
    city: '',
    category: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row: Post) => {
  editingPost.value = row
  postForm.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row: Post) => {
  ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const response = await userPostApi.delete(row.id)
      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        fetchPosts()
      }
    } catch (error) {
      console.error('删除文章失败:', error)
      ElMessage.error('删除文章失败')
    }
  })
}

const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const response = editingPost.value
          ? await userPostApi.update(editingPost.value.id, postForm.value)
          : await userPostApi.create(postForm.value)
        
        if (response.data.code === 200) {
          ElMessage.success(editingPost.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          fetchPosts()
        }
      } catch (error) {
        console.error(editingPost.value ? '更新文章失败:' : '创建文章失败:', error)
        ElMessage.error(editingPost.value ? '更新文章失败' : '创建文章失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchPosts()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchPosts()
}

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style> 